<template>
  <dt-modal-edit ref='modal' :title='title' :width='660' @ok='onOk' :loading='loading'  @cancelData="cancelData">
    <dt-info :options='option' ref="dtInfo"  :label-width='120' :info="info"></dt-info>
  </dt-modal-edit>
</template>

<script>
  import moment from 'moment'
  import Opt from '../opt/ContractOpt.js'
  import contractMgr from '@/biz/buildingManagement/contract.js'
  
  export default {
    data() {
      return {
        title: '新建合同',
        info: {
          attachList:[],
          contractBeginTime:null,
          contractEndTime:null,
          contractName:'',
          endType:'',
          housesId:''
        },
        option:[],
        prev: null,
        next: null,
        loading: false,
      }
    },
    methods: {
      show(isCreate) {
        this.option = new Opt(this.info, this.prev, this.next, isCreate).opts
        this.$refs.modal.show()
      },
      cancelData(){
        this.$emit('abolish')
      },
      hide() {
        this.$refs.modal.hide()
      },
      create(opt) {
        this.title = '新建合同'
        let contractBeginTime = null
        if (opt.prev) {
          contractBeginTime = opt.prev.endType == '1' 
            ? moment(opt.prev.contractEndTime).add(1, 'days').format('YYYY-MM-DD') 
            : moment(opt.prev.contractBeginTime).add(1, 'days').format('YYYY-MM-DD')
        }
        this.info = {
          contractName: null,
          contractBeginTime,
          endType: '1',
          contractEndTime: null,
          attachList: []
        }
        this.prev = opt.prev
        this.next = opt.next
        this.show(true)
      },
      edit(opt) {
        console.log(opt,'编辑合同');
        this.title = '编辑合同'
        this.info = opt.info
        this.prev = opt.prev
        this.next = opt.next
        this.show(false)
      },
      onOk() {
        this.$refs.dtInfo.validate().then((res) => {
          if (res) {
            if (this.onValidate()) {
              this.info.attachList&&this.info.attachList.forEach(item=>{
                item.imageName = item.name
                item.imageURL = item.url
              })
              this.loading = true            
              contractMgr.saveContract(this.info).then((res) => {
                this.loading = false
                this.$emit('success')
                this.hide()
              }).catch(err => {
                this.loading = false
              })
            }
          }

        })
        
      },
      onValidate() {
        let valid = true
        if (this.info.endType == '1' && (moment(this.info.contractBeginTime) > moment(this.info.contractEndTime))) {
          this.$Message.error('结束日期不可小于开始日期')
          valid = false
        }
      
        return valid
      },
    }
  }
</script>

<style lang="scss" scoped>
</style>
